#!/usr/bin/env bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - clean_repos
# - one_file
# - name
# - baseurl
# - enabled
# - priority
# - gpgcheck
# - gpgkey
# - metalink
# - metadata_expire
# END ENVIRONMENT VARIABLES

write_repo_config() 
{
	[ -n "$name" ] || { echo "Error: 'name' is not set"; return 1; }
    [ -n "$baseurl" ] || { echo "Error: 'baseurl' is not set"; return 1; }

    local cfgfile=$1
	cat <<-EOF >> $cfgfile
	[$name]
	name=$name
	baseurl=$baseurl
	enabled=${enabled:-1}
	gpgcheck=${gpgcheck:-1}
	EOF

    [ -n "$priority" ] && echo "priority=$priority" >> "$cfgfile"
    [ -n "$gpgkey" ] && echo "gpgkey=$gpgkey" >> "$cfgfile"
    [ -n "$metalink" ] && echo "metalink=$metalink" >> "$cfgfile"
    [ -n "$metadata_expire" ] && echo "metadata_expire=$metadata_expire" >> "$cfgfile"
}

add_repo() 
{
    local cfgfile="/etc/yum.repos.d/$name.repo"
    write_repo_config "$cfgfile"
    dnf -y makecache
}

add_repo_one_file() 
{
    local one_file_lower=$(echo "$one_file" | tr '[:upper:]' '[:lower:]')
    case $one_file_lower in
        1|yes|true)
            repo_count=$(ls /etc/yum.repos.d/*.repo 2>/dev/null | wc -l)
            
            if [ "$repo_count" -gt 1 ]; then
                echo "Error: More than one .repo file found in /etc/yum.repos.d/"
                exit 1
            elif [ "$repo_count" -eq 0 ]; then
                add_repo
            else
                repo_file=$(ls /etc/yum.repos.d/*.repo)
                write_repo_config "$repo_file"
            fi
            ;;
        *)
            echo "Warning: unknown param dnf-repo.one_file=$one_file"
            ;;
    esac
}

clean_repos() 
{
    [ -z "$clean_repos" ] && return

    # True/TRUE/Yes... are valid in clean_repos
    local clean_repos_lower=$(echo "$clean_repos" | tr '[:upper:]' '[:lower:]')
    case $clean_repos_lower in
        1|yes|true)
            mv /etc/yum.repos.d/*.repo /tmp/
            ;;
        *)
            echo "Warning: unknown param dnf-repo.clean_repos=$clean_repos"
            ;;
    esac
}

clean_repos
# one_file Indicates whether to add repositories in multiple or a single .repo file.
# - If empty, multiple .repo files will be added.
# - If set, a single .repo file will be added, containing multiple repositories.
if [ -n "$one_file" ]; then
	add_repo_one_file
else
	add_repo
fi
